package com.oracle.third.service.mobile.listener;

import com.alibaba.fastjson.JSONObject;
import com.oracle.third.service.mobile.listener.service.MobileService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 手动确认模式实现ChannelAwareMessageListener接口
 *
 * 第二个参数为是否把比当前消息之前的消息全部都拒掉
 * 使用channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);手动确认
 *
 * 第二个参数为是否把比当前消息之前的消息全部都拒掉
 * 第三个参数为设置是否重新入队
 *  channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
 *
 */
@Component
public class MobileQueueListener implements ChannelAwareMessageListener {

    @Autowired
    private MobileService mobileService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String phone = new String(message.getBody());
        phone = (String) JSONObject.parse(phone);
        try {
            this.mobileService.sendMobileRandom(phone);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            e.printStackTrace();
        }
    }
}
